var express = require('express');
var router = express.Router();
var bcrypt = require('bcryptjs')
var NodeRSA = require('node-rsa')
var moment = require('moment')
const db = require('../sql/connect')
var broadcast = require('../utils/broadcast')
var urlList = require('../config/urlList')

router.post('/', async (req, res, next) => {
    if (req.body.flag != 1) {
        let sql = 'select * from useritem where username = ?';
        let data = req.body;
        db.base(sql, data.username, (response) => {
            if (response.results.length != 0) {
                res.json({
                    "type": "error",
                    "content": "注册的工号已经存在"
                });
                return
            } else {
                const saltRounds = 10
                const salt = bcrypt.genSaltSync(saltRounds);
                var key = new NodeRSA({ b: 512 })
                let sql = 'INSERT INTO useritem SET ?';
                let userInfo = {
                    username: data.username,
                    password: bcrypt.hashSync(data.password, salt),
                    mail: data.mail,
                    institution: data.institution,
                    date: moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'),
                    pubKey: key.exportKey('public')
                }
                db.base(sql, userInfo, (results) => {
                    //这里注册sql失败error.type==0
                    if (results.type == 0) {
                        res.json({
                            "type": "error",
                            "content": "注册失败"
                        });
                    } else {
                        req.body = userInfo
                        req.body.flag = 1
                        console.log(req.body)
                        broadcast.broadcastToAll(req, urlList, "/register")
                        userInfo.privateKey = key.exportKey('private')
                        res.json({
                            "type": "success",
                            "content": key.exportKey('private')
                        });
                    }

                });
            }
        });
    } else {
        let userInfo = {
            username: req.body.username,
            password: req.body.password,
            mail: req.body.mail,
            institution: req.body.institution,
            date: req.body.date,
            pubKey: req.body.pubKey
        }
        db.base(sql, userInfo, (results) => {
            //这里注册sql失败error.type==0
            if (results.type == 0) {
                res.json({
                    "type": "error",
                    "content": "注册失败"
                });
            } else {
                userInfo.privateKey = key.exportKey('private')
                res.json({
                    "type": "success",
                    "content": key.exportKey('private')
                });
            }

        });
    }
});

module.exports = router;